package com.yanqu.road.web.mgr;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.web.RecommendServerReturnParam;
import com.yanqu.road.logic.redis.RedisServerCreateRoleHelper;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.AutoOpenServerMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.web.WebServer;
import redis.clients.jedis.Tuple;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class RoleCreateCountMgr extends TempMgr {

    private static Map<Long, Integer> serverRoleCreateCountMap = new ConcurrentHashMap<>();

    private static Map<Long, Integer> serverValidCreateCountMap = new ConcurrentHashMap<>();

    public static Map<Long, Integer> getServerRoleCreateCountMap() {
        return serverRoleCreateCountMap;
    }

    public static void setServerRoleCreateCountMap(Map<Long, Integer> serverRoleCreateCountMap) {
        RoleCreateCountMgr.serverRoleCreateCountMap = serverRoleCreateCountMap;
    }

    public static int getRoleCreateCountByServerId(long serverId) {
        if (serverRoleCreateCountMap.containsKey(serverId)) {
            return serverRoleCreateCountMap.get(serverId);
        } else {
            return 0;
        }
    }

    public static int getValidCreateCountByServerId(long serverId) {
        if (serverValidCreateCountMap.containsKey(serverId)) {
            return serverValidCreateCountMap.get(serverId);
        } else {
            return 0;
        }
    }

    @Override
    public boolean reloadData() throws Exception {
        loadRoleCreateCount();
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static void loadRoleCreateCount() {
        if (!WebServer.getInstance().isUserCenter()) {
            // 非用户中心不需要加载 TODO return;
            return;
        }
        try {
            Set<Tuple> tupleSet = RedisServerCreateRoleHelper.getRoleCreateCount();
            Iterator<Tuple> iterator = tupleSet.iterator();
            while(iterator.hasNext()) {
                Tuple tuple = iterator.next();
                long serverId = Long.valueOf(tuple.getElement());
                int num = (int) tuple.getScore();
                serverRoleCreateCountMap.put(serverId, num);
            }

            getLogger().info("create count:{}", JSONObject.toJSONString(serverRoleCreateCountMap));
        } catch (Exception ex) {
            getLogger().error(ex);
        }

        //新加有效创角
        try {
            Set<Tuple> tupleSet = RedisServerCreateRoleHelper.getRoleCreateCount2();
            Iterator<Tuple> iterator = tupleSet.iterator();
            while(iterator.hasNext()) {
                Tuple tuple = iterator.next();
                long serverId = Long.valueOf(tuple.getElement());
                int num = (int) tuple.getScore();
                serverValidCreateCountMap.put(serverId, num);
            }

            getLogger().info("valid count:{}", JSONObject.toJSONString(serverValidCreateCountMap));
        } catch (Exception ex) {
            getLogger().error(ex);
        }
    }

    /**
     * 获取一个推荐区服
     * @return
     */
    public static RecommendServerReturnParam getRecommendServerInfo(List<ServerInfo> serverInfoList) {
        if (serverInfoList == null || serverInfoList.size() == 0) {
            return null;
        }


        List<ServerInfo> recommendList = new ArrayList<>();
        List<Long> serverIdList = new ArrayList<>();
        for (ServerInfo serverInfo : serverInfoList) {
            if (!serverInfo.isOpenSplitFlow()) {
                continue;
            }

            // 期待状态的不能加入到推荐区服
            if (ServerListMgr.isComingSoon(serverInfo)) {
                continue;
            }

            // 预创角不加入推荐区服
            if(ServerListMgr.isPreRole(serverInfo.getServerId())){
                continue;
            }

            if (getNewRoleCreateCount(serverInfo) < serverInfo.getCreateRoleCountLimit()) {
                recommendList.add(serverInfo);
                serverIdList.add(serverInfo.getServerId());
            }
        }

        if (recommendList.size() == 0) {
            return null;
        }

        int randomIndex = new Random().nextInt(recommendList.size());
        ServerInfo serverInfo = recommendList.get(randomIndex);
        return new RecommendServerReturnParam(serverIdList, serverInfo);
    }

    /**
     * 按类型维度获取当前限流监控人数
     */
    public static int getNewRoleCreateCount(ServerInfo serverInfo){
        if(null == serverInfo){
            return 0;
        }
        int type = AutoOpenServerMgr.getAutoOpenRoleLimitType(serverInfo.getChannelId());
        if(type == 1){
            return getRoleCreateCountByServerId(serverInfo.getServerId());
        }else if(type == 2){
            return getValidCreateCountByServerId(serverInfo.getServerId());
        }else {
            return RegisterPlayerNumMgr.getRegisterNumByServerId(serverInfo.getServerId());
        }
    }
}

